import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:test_flutter/cache/UserDataCache.dart';
import 'package:test_flutter/dio/Api.dart';
import 'package:test_flutter/dio/DioUtil.dart';
import 'package:test_flutter/model/response/user_model.dart';
import 'package:test_flutter/model/scoped_model/main_model.dart';
import 'package:test_flutter/utils/ToastUtil.dart';
import 'package:test_flutter/utils/factory/Fit.dart';
import 'package:test_flutter/widgets/Button.dart';
import 'package:test_flutter/widgets/EditText2.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';



class EditInfoPage extends StatefulWidget {
  EditInfoPage();
  @override
  EditInfoState createState() => new EditInfoState();
}

class EditInfoState extends State<EditInfoPage> {
  bool _saving = false;
  bool isEditable = false;

  String name = '';
  String area = '';
  String address = '';
  String email = '';
  String IdNo = '';

  String gender = '';   //1 男 0 女
  String birthday = '';

  int year;
   int month;
   int date;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getMemberInfo();
  }

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<MainModel>(builder: (context, child, model) {
      return new Theme(
          data: new ThemeData(
            primarySwatch: Colors.grey,
            brightness: Brightness.light,
          ),
          child: new Scaffold(
            resizeToAvoidBottomPadding: true, //输入框抵住键盘
            backgroundColor: Colors.white,
            appBar: PreferredSize(
                child: Container(
                  decoration: BoxDecoration(
                      gradient: LinearGradient(colors: [
                    Color(0xFF3C8CE7),
                    Color(0xFF00EAFF),
                  ])),
                  child: new AppBar(
                    primary: true,
                    title: new Text('个人信息'),
                    backgroundColor: Colors.transparent,
                    actions: <Widget>[
                      new IconButton(
                          icon: new Icon(
                            Icons.edit,
                            color:
                                isEditable ? Colors.limeAccent : Colors.white,
                          ),
                          tooltip: 'Add Alarm',
                          onPressed: () {
                            setState(() {
                              isEditable = !isEditable;
                            });
                          }),
                    ],
                  ),
                ),
                preferredSize: new Size(Fit.scaleX(1080), kToolbarHeight)),
            body: ModalProgressHUD(
              inAsyncCall: _saving,
              child: new SingleChildScrollView(
                child: new Column(
                  children: <Widget>[
                    EditText2(
                      '请填写姓名',
                      'images/name.png',
                      value: name,
                      enabled: isEditable,
                      onChanged: (value) {
                        name = value;
                      },
                    ),
                    new EditText2(
                      '请选择出生日期',
                      'images/birthday.png',
                      value: birthday,
                      enabled: false,
                      onChanged: (value) {
                        birthday = value;
                      },
                      onTab: (){
                        if(isEditable){

                          DateTime now = new DateTime.now();
                          year = now.year;
                          month = now.month;
                          date = now.day;


                          DatePicker.showDatePicker(
                            context,
                            showTitleActions: true,
                            minYear: 1960,
                            maxYear: 2080,
                            initialYear: year,
                            initialMonth: month,
                            initialDate: date,
                            cancel: Text('取消',style: TextStyle(color: Colors.grey),),
                            confirm: Text('确认',style: TextStyle(color: Colors.blue),),
                            onChanged: (year, month, date) {
                              print('${year}-${month}-${date}');
                            },
                            onConfirm: (year, month, date) {
                              setState(() {
                                birthday = '${year}-${month}-${date}';
                              });
                            },
                          );
                        }
                      },
                    ),
                    //editBirthday,
                    EditText2(
                      '请填写地区',
                      'images/area.png',
                      value: area,
                      enabled: isEditable,
                      onChanged: (value) {
                        area = value;
                      },
                    ),
                    EditText2(
                      '请填写住址',
                      'images/address.png',
                      value: address,
                      enabled: isEditable,
                      onChanged: (value) {
                        address = value;
                      },
                    ),
                    new EditText2(
                      '请填邮件地址',
                      'images/email.png',
                      value: email,
                      enabled: isEditable,
                      onChanged: (value) {
                        email = value;
                      },
                    ),
                    new EditText2(
                      '请填身份证号',
                      'images/id_card.png',
                      value: IdNo,
                      enabled: isEditable,
                      onChanged: (value) {
                        IdNo = value;
                      },
                    ),
                    new EditText2(
                      '请选择性别',
                      'images/sex.png',
                      value: gender,
                      enabled: false,
                      onChanged: (value) {
                        gender = value;
                      },
                      onTab: () {
                        if (isEditable) {
                          showModalBottomSheet(
                              context: context,
                              builder: (BuildContext context) {
                                return new Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: <Widget>[
                                    new ListTile(
                                      title: Center(child: new Text("男")),
                                      onTap: () async {

                                        setState(() {
                                          gender = '男';

                                        });
                                        Navigator.pop(context);

                                      },
                                    ),
                                    new ListTile(
                                      title: Center(child: new Text("女")),
                                      onTap: () async {
                                        setState(() {
                                          gender = '女';
                                        });
                                        Navigator.pop(context);
                                      },
                                    ),
                                  ],
                                );
                              });
                        }
                      },
                    ),

                    Offstage(
                      offstage: !isEditable, //这里控制
                      child: new Padding(
                        padding: EdgeInsets.only(top: Fit.scaleY(200)),
                        child: new Button('确定', onPressed: setOnclick),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ));
    });
  }

  void setOnclick() {
    _updateMemberInfo();
  }

  ///获取会员信息
  _getMemberInfo() async {

    setState(() {
      _saving = true;
    });

    DioUtil.getInstance(context).get(Api.getMemberInfo, (response) {
      if (response.data['code'] == 1) {
        setState(() {
          name = response.data['data']['Name'] == null
              ? ''
              : response.data['data']['Name'];
          area = response.data['data']['Area'] == null
              ? ''
              : response.data['data']['Area'];
          address = response.data['data']['Address'] == null
              ? ''
              : response.data['data']['Address'];
          email = response.data['data']['Email'] == null
              ? ''
              : response.data['data']['Email'];


          IdNo = response.data['data']['IdNo'] == null
              ? ''
              : response.data['data']['IdNo'];


          if(response.data['data']['Gender'] == null){
            gender = '';
          }else{
            response.data['data']['Gender'] == 1 ? gender = '男' :gender = '女';
          }



          birthday = response.data['data']['Birthday'] == null
              ? ''
              : (response.data['data']['Birthday']).substring(0,"yyyy-MM-dd ".length-1);

        });
      } else {
        ToastUtil.showToast(response.data['msg']);
      }

      setState(() {
        _saving = false;
      });
    }, errorCallBack: (errorMsg) {
      print("error=========================:" + errorMsg);
      ToastUtil.showToast(errorMsg);
      setState(() {
        _saving = false;
      });
    });
  }

  ///编辑会员信息
  _updateMemberInfo() async {



    if (name.length == 0) {
      ToastUtil.showToast('请填写姓名');
      return;
    }
     if (birthday.length == 0) {
      ToastUtil.showToast('请填写出生日期');
      return;
    }
    if (area.length == 0) {
      ToastUtil.showToast('请填写地区');
      return;
    }
    if (address.length == 0) {
      ToastUtil.showToast('请填写住址');
      return;
    }

    if (email.length == 0) {
      ToastUtil.showToast('请填写邮件地址');
      return;
    }
    if (IdNo.length == 0) {
      ToastUtil.showToast('请填身份证号');
      return;
    }

    setState(() {
      _saving = true;
    });

    Map<String, String> requestMap = new Map();
    UsersModel user = await UserDataCache.getInstance().getUser();
    requestMap['Id'] = user.Id.toString();
    requestMap['Name'] = name;
    requestMap['Email'] = email;
    requestMap['IdNo'] = IdNo;
    requestMap['Area'] = area;
    requestMap['Address'] = address;
    requestMap['Birthday'] = birthday;
    requestMap['Gender'] = (gender=='男')? '1' : '0';


    DioUtil.getInstance(context).post(
        Api.updateMemberInfo,
        (response) {
          if (response.data['code'] == 1) {
            ToastUtil.showToast('信息编辑成功');
            user.Area = area;
            user.Name = name;
            user.Address = address;
            UserDataCache.getInstance().setUser(context, user);

            Navigator.of(context).pop();
          } else {
            ToastUtil.showToast(response.data['msg']);
          }

          setState(() {
            _saving = false;
          });
        },
        data: requestMap,
        errorCallBack: (errorMsg) {
          print("error=========================:" + errorMsg);
          ToastUtil.showToast(errorMsg);
          setState(() {
            _saving = false;
          });
        });

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

  }
}
